﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Joyintech.Model.inpiao365;
using Joyintech.BLL.inpiao365;
using Joyintech.Common;
using System.IO;
using System.Text;
using System.Data;

namespace Joyintech.Admin.inpiao365.general.createhtml
{
    /// <summary>
    /// 生成栏目频道页面
    /// </summary>
    public partial class createChannel : System.Web.UI.Page
    {
        #region 页面初始化

        /// <summary>
        /// 页面初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            { 
                //加载栏目列表
                DataBindNode(0, "");
            }
        }

        #endregion

        #region 加载栏目列表

        /// <summary>
        /// 加载栏目列表
        /// </summary>
        /// <param name="ParentId"></param>
        private void DataBindNode(int ParentId,string strFront)
        { 
            List<systemNode> list = new List<systemNode>();

            list = new systemNode_BLL().GetModelList("ParentID=" + ParentId + " order by NodeOrder");

            if (list != null && list.Count > 0)
            {
                strFront += "-";

                foreach (systemNode nodeModel in list)
                {
                    ListItem item = new ListItem(strFront + nodeModel.NodeName, nodeModel.NodeID.ToString());

                    this.listSystemNode.Items.Add(item);

                    DataBindNode(nodeModel.NodeID, strFront);
                }
            }
        }

        #endregion

        #region 创建栏目页面

        /// <summary>
        /// 分别创建栏目页面
        /// </summary>
        private void Create()
        {
            string selectedNodeId = string.Empty;

            foreach (ListItem item in this.listSystemNode.Items)
            {
                if (item.Selected)
                {
                    selectedNodeId += item.Value + ",";
                }
            }

            if (selectedNodeId == "")
            {
                MessageBox.Show(this, "没有选择需要生成的栏目！");
                return;
            }
            else
            {
                selectedNodeId = Utils.ClearLastChar(selectedNodeId);
            }

            List<systemNode> list = new List<systemNode>();

            list = new systemNode_BLL().GetModelList("NodeId in (" + selectedNodeId + ") order by NodeOrder");

            if (list != null && list.Count > 0)
            {
                foreach (systemNode nodeModel in list)
                {
                    systemTemplate model = new systemTemplate_BLL().GetModel(nodeModel.ChannelTemplateID.Value);

                    if (model == null)
                    {
                        MessageBox.Show(this, "页面生成已停止，没有检索到栏目\"" + nodeModel.NodeName + "\"对应的模板（模板编号：" + nodeModel.ChannelTemplateID.Value + "）！");
                        return;
                    }

                    string templatefileName = Server.MapPath("../../templates/" + model.RelatedFileName);

                    if (model.TemplateType == "ChannelTemplate")
                    {
                        templatefileName = Server.MapPath("../../templates/channel/" + model.RelatedFileName);
                    }
                    else if (model.TemplateType == "ContentTemplate")
                    {
                        templatefileName = Server.MapPath("../../templates/content/" + model.RelatedFileName);
                    }

                    //检查模板文件是否存在
                    if (!Utils.FileExists(templatefileName))
                    {
                        MessageBox.Show(this, "栏目\"" + nodeModel.NodeName + "\"对应的模板文件\"" + model.RelatedFileName + "\"不存在，可能已被移除，请确认！");
                        return;
                    }

                    VelocityHelper vh = new VelocityHelper();
                    vh.Init(@"~/templates/channel/");

                    //单页显示条数
                    int ItemsPerPage = 15;

                    if (nodeModel.ItemsPerPage != null)
                    {
                        ItemsPerPage = nodeModel.ItemsPerPage.Value;  
                    }

                    //获取列表总条数
                    int ContentNum = nodeModel.ContentNum;

                    if (nodeModel.SelectTableCount != "")
                    {
                        ContentNum = new pageSplit_BLL().GetPagerTotalCount(nodeModel.SelectTableCount);
                    }

                    //判断分页数据是否超过指定的条数
                    int PageCount = ContentNum % ItemsPerPage;

                    if (PageCount > 0)
                    {
                        PageCount = ContentNum / ItemsPerPage + 1;
                    }
                    else
                    {
                        PageCount = ContentNum / ItemsPerPage;
                    }

                    if (PageCount == 0)
                    {
                        string bllName = ConfigHelper.GetConfigString("BLL");

                        System.Reflection.Assembly BLL = System.Reflection.Assembly.Load(bllName);

                        Type[] types = BLL.GetTypes();

                        // 遍历程序集中的类
                        foreach (Type item in types)
                        {
                            string className = item.ToString().Replace(bllName + ".", "");

                            object stu = item.Assembly.CreateInstance(item.ToString());

                            //添加页面操作类BLL
                            vh.Put(className, stu);
                        }

                        //页面数
                        vh.Put("pages", PageCount);

                        //栏目实体
                        vh.Put("channel", nodeModel);

                        string html = vh.Display(model.RelatedFileName);

                        string directory = model.FileCreatePath + "\\";

                        //判断栏目页面文件夹是否存在，如果不存在则创建
                        if (!Directory.Exists(directory))
                        {
                            Directory.CreateDirectory(directory);
                        }

                        //栏目页面名称，默认只有一页
                        string fileName = directory + nodeModel.NodeID.ToString() + model.CreatedFileExtName;
                        //string fileName = directory + model.CreatedFileFullName.ToString() + model.CreatedFileExtName;

                        //if (model.CreatedFileFullName.Trim().Equals(""))
                        //{
                        //    fileName = directory + nodeModel.NodeID.ToString() + model.CreatedFileExtName;
                        //}

                        //栏目有分页且页数>1时，则每个页面名称后面加“_页索引”
                        if (PageCount > 1)
                        {
                            fileName = directory + nodeModel.NodeID.ToString() + model.CreatedFileExtName;
                        }

                        StreamWriter objSw = new StreamWriter(fileName, false, Encoding.GetEncoding(model.TemplateCharset));
                        objSw.WriteLine(html);
                        objSw.Flush();
                        objSw.Close();
                    }
                    else
                    {
                        //返回生成多个列表页面
                        for (int CurrentPageIndex = 1; CurrentPageIndex <= PageCount; CurrentPageIndex++)
                        {
                            PageSplit pager = new PageSplit();

                            pager.SetPage(vh, CurrentPageIndex, nodeModel.NodeID.ToString(), PageCount);

                            //当前页记录开始索引
                            int StartRowNum = ItemsPerPage * (CurrentPageIndex - 1) + 1;

                            //当前面记录结束索引
                            int EndRowNum = ItemsPerPage * CurrentPageIndex;

                            if (nodeModel.SelectTable != "")
                            {
                                DataSet ds = new pageSplit_BLL().GetPagerList(nodeModel.SelectTable, nodeModel.SelectTableOrderBy, StartRowNum, EndRowNum);

                                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                                {
                                    //向模板中加载列表数据
                                    vh.Put("contents", ds.Tables[0]);
                                }
                                else
                                {
                                    //向模板中加载空列表数据
                                    vh.Put("contents", new DataTable());
                                }
                            }
                            else
                            {
                                //获取当前分页的内容列表
                                List<systemNodeContent> contentList = new systemNodeContent_BLL().GetModelList(nodeModel.NodeID, StartRowNum, EndRowNum);
                                vh.Put("contents", contentList);
                            }

                            string bllName = ConfigHelper.GetConfigString("BLL");

                            System.Reflection.Assembly BLL = System.Reflection.Assembly.Load(bllName);

                            Type[] types = BLL.GetTypes();

                            // 遍历程序集中的类
                            foreach (Type item in types)
                            {
                                string className = item.ToString().Replace(bllName + ".", "");

                                object stu = item.Assembly.CreateInstance(item.ToString());

                                //添加页面操作类BLL
                                vh.Put(className, stu);
                            }

                            //页面数
                            vh.Put("pages", PageCount);
                            vh.Put("page", CurrentPageIndex);

                            //栏目实体
                            vh.Put("channel", nodeModel);

                            string html = vh.Display(model.RelatedFileName);

                            string directory = model.FileCreatePath + "\\";

                            //判断栏目页面文件夹是否存在，如果不存在则创建
                            if (!Directory.Exists(directory))
                            {
                                Directory.CreateDirectory(directory);
                            }

                            //栏目页面名称，默认只有一页
                            string fileName = directory + nodeModel.NodeID.ToString() + model.CreatedFileExtName;
                            //string fileName = directory + model.CreatedFileFullName.ToString() + model.CreatedFileExtName;

                            //if (model.CreatedFileFullName.Trim().Equals(""))
                            //{
                            //    fileName = directory + nodeModel.NodeID.ToString() + model.CreatedFileExtName;
                            //}

                            //栏目有分页且页数>1时，则每个页面名称后面加“_页索引”
                            if (PageCount > 1)
                            {
                                fileName = directory + nodeModel.NodeID.ToString() + "_" + CurrentPageIndex.ToString() + model.CreatedFileExtName;

                                //if (model.CreatedFileFullName.Trim().Equals(""))
                                //{
                                //    fileName = directory + nodeModel.NodeID.ToString() + "_" + CurrentPageIndex.ToString() + model.CreatedFileExtName;
                                //}
                            }

                            StreamWriter objSw = new StreamWriter(fileName, false, Encoding.GetEncoding(model.TemplateCharset));
                            objSw.WriteLine(html);
                            objSw.Flush();
                            objSw.Close();
                        }
                    }
                }
            }
        }

        #endregion

        #region 删除生成的栏目页面

        /// <summary>
        /// 删除生成的栏目页面
        /// </summary>
        private void DeleteChannelPage()
        {
            string selectedNodeId = string.Empty;

            foreach (ListItem item in this.listSystemNode.Items)
            {
                if (item.Selected)
                {
                    selectedNodeId += item.Value + ",";
                }
            }

            if (selectedNodeId == "")
            {
                MessageBox.Show(this, "没有选择栏目！");
                return;
            }
            else
            {
                selectedNodeId = Utils.ClearLastChar(selectedNodeId);
            }

            List<systemNode> list = new List<systemNode>();

            list = new systemNode_BLL().GetModelList("NodeId in (" + selectedNodeId + ") order by NodeOrder");

            if (list != null && list.Count > 0)
            {
                foreach (systemNode nodeModel in list)
                {
                    systemTemplate model = new systemTemplate_BLL().GetModel(nodeModel.ChannelTemplateID.Value);

                    if (model == null)
                    {
                        MessageBox.Show(this, "页面生成已停止，没有检索到栏目\"" + nodeModel.NodeName + "\"对应的模板（模板编号：" + nodeModel.ChannelTemplateID.Value + "）！");
                        return;
                    }

                    VelocityHelper vh = new VelocityHelper();
                    vh.Init(@"~/templates/channel/");

                    //单页显示条数
                    int ItemsPerPage = 15;

                    //判断分页数据是否超过指定的条数
                    int PageCount = nodeModel.ContentNum % ItemsPerPage;

                    if (PageCount > 0)
                    {
                        PageCount = nodeModel.ContentNum / ItemsPerPage + 1;
                    }
                    else
                    {
                        PageCount = nodeModel.ContentNum;
                    }

                    //返回生成多个列表页面
                    for (int CurrentPageIndex = 1; CurrentPageIndex <= PageCount; CurrentPageIndex++)
                    {
                        PageSplit pager = new PageSplit();

                        pager.SetPage(vh, CurrentPageIndex, nodeModel.NodeID.ToString(), PageCount);

                        //当前页记录开始索引
                        int StartRowNum = ItemsPerPage * (CurrentPageIndex - 1) + 1;
                        //当前面记录结束索引
                        int EndRowNum = ItemsPerPage * CurrentPageIndex;

                        //string directory = ConfigHelper.GetConfigString("ChannelPath");

                        string directory = model.FileCreatePath + "\\";

                        //判断栏目页面文件夹是否存在，如果不存在则创建
                        if (!Directory.Exists(directory))
                        {
                            Directory.CreateDirectory(directory);
                        }
                        //栏目页面名称，默认只有一页
                        string fileName = directory + nodeModel.NodeID.ToString() + model.CreatedFileExtName;

                        //栏目有分页且页数>1时，则每个页面名称后面加“_页索引”
                        if (PageCount > 1)
                        {
                            fileName = directory + nodeModel.NodeID.ToString() + "_" + CurrentPageIndex.ToString() + model.CreatedFileExtName;
                        }

                        //执行删除
                        File.Delete(fileName);
                    }
                }
            }
        }

        #endregion

        #region 页面按钮事件

        /// <summary>
        /// 页面生成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCreateChannel_Click(object sender, EventArgs e)
        {
            Create();

            MessageBox.Show(this, "生成成功！");
        }

        /// <summary>
        /// 页面删除事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDeleteChannel_Click(object sender, EventArgs e)
        {
            DeleteChannelPage();

            MessageBox.Show(this, "删除成功！");
        }

        #endregion
    }
}